package org.example.easybuy.controller;

import org.example.easybuy.annotation.PermissionCheck;
import org.example.easybuy.entity.User;
import org.example.easybuy.entity.UserAddress;
import org.example.easybuy.service.UserAddressService;
import org.example.easybuy.service.UserService;
import org.example.easybuy.util.CustomResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
@RequestMapping("/address")
@RestController
public class MemberAddressController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserAddressService userAddressService;

    @PostMapping("/addUserAddress")
    public CustomResult addUserAddress(@RequestBody UserAddress userAddress)
    {
        User user=userService.getUserByLoginName(userAddress.getLoginName());
        userAddress.setUserId(user.getId());
        userAddress.setCreateTime(new Date());
        if(userAddressService.addUserAddress(userAddress))
        {
            return CustomResult.successResult().addResult("isAdd","success");
        }
        return CustomResult.errorResult(500,"添加地址出错了");
    }

    @PermissionCheck("0")
    @GetMapping("/getAddressList")
    public CustomResult selectUserAddress(String loginName)
    {
        return CustomResult.successResult().addResult("addressList",userAddressService.selectAddressByLoginName(loginName));
    }

    @PermissionCheck("0")
    @GetMapping("/delAddress")
    public CustomResult delAddress(int id)
    {
        if(userAddressService.delAddress(id))
        {
            return CustomResult.successResult().addResult("isDelete","yes");
        }
        return CustomResult.errorResult(500,"删除出错了");
    }

    @PermissionCheck("0")
    @GetMapping("/changeDefault")
    public CustomResult changeDefault(int id,int userId)
    {
        if(userAddressService.changeDefault(id,userId))
        {
            return CustomResult.successResult().addResult("isChange","yes");
        }
        return CustomResult.errorResult(500,"fail");
    }

    @PermissionCheck("0")
    @PostMapping("/updateUserAddress")
    public CustomResult updateUserAddress(@RequestBody UserAddress userUpdateAddress)
    {
        if(userAddressService.updateUserAddress(userUpdateAddress))
        {
            return CustomResult.successResult().addResult("isUpdate","success");
        }
        return CustomResult.errorResult(500,"修改出错了");
    }

}
